package com.dmzc.stage2.chapter28;


import org.w3c.dom.events.EventException;

import java.lang.reflect.Executable;
import java.util.concurrent.Executor;

public class EventBus implements Bus {
    //维护Subcriber的注册表
    private final Registry registry = new Registry();
    private String busName;
    private final static String DEFAULT_BUS_NAME = "default";
    private final static String DEFAULT_TOPIC="default_topic";
    //用于分发广播消息
    private final Dispatcher dispatcher;
    public EventBus(){
        this(DEFAULT_BUS_NAME,null,Dispatcher.SEQ_EXECUTOR_SERVICE);
    }
    public EventBus(String busName){
        this(busName,null,Dispatcher.SEQ_EXECUTOR_SERVICE);
    }
    public EventBus(EventExceptionHandler eventExceptionHandler){
        this(DEFAULT_BUS_NAME,eventExceptionHandler,Dispatcher.SEQ_EXECUTOR_SERVICE);
    }
     EventBus(String busName, EventExceptionHandler eventExceptionHandler, Executor executor){
        this.busName=busName;
        this.dispatcher=Dispatcher.newDispacher(eventExceptionHandler,executor);
    }
    /**
     * 将某个对象注册到Bus上
     *
     * @param subcriber
     */
    @Override
    public void register(Object subcriber) {
        this.registry.bind(subcriber);
    }

    /**
     * 将某个对象从bus上取消注册
     *
     * @param subscriber
     */
    @Override
    public void unregister(Object subscriber) {
        this.registry.unbind(subscriber);
    }

    /**
     * 提交event到默认的topic
     *
     * @param event
     */
    @Override
    public void post(Object event) {
        this.post(event,DEFAULT_TOPIC);
    }

    /**
     * 提交event到指定的topic
     *
     * @param event
     * @param topic
     */
    @Override
    public void post(Object event, String topic) {
        this.dispatcher.dispatch(this,registry,event,topic);
    }

    /**
     * 关闭bus
     */
    @Override
    public void close() {
        this.dispatcher.close();
    }

    /**
     * 返回Bus名称
     *
     * @return
     */
    @Override
    public String getBusName() {
        return this.busName;
    }
}
